package com.liyiyan.note.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
  
public class GetImageService{ 
	private static final String path= Environment.getExternalStorageDirectory()+"/teaShop";
	public static BitmapDrawable getImage(String image_url) throws Throwable{

		URL url = new URL(image_url);
		String[] filenames = url.getFile().split("/");
		String filename = filenames[filenames.length-1];
		String dirString = path;
		File dirFile = new File(dirString);
		if (!dirFile.exists()){
			dirFile.mkdir();
		}
		File temp = new File(dirFile, filename);
		InputStream inStream=null;
		byte[] buffer;
		
		String sdStatus = Environment.getExternalStorageState();
		//
		if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {

			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			inStream = conn.getInputStream();//ͨ����������ȡͼƬ���
			buffer = HelperTool.readInputStream(inStream);

		} else {
			if (!temp.exists()){
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5 * 1000);
				inStream = conn.getInputStream();//ͨ����������ȡͼƬ���
				buffer = HelperTool.readInputStream(inStream);
				saveToSD(temp, buffer); //save as cache

			} else {
				//Log.i(TAG, "FILE");
				//file is cached just read it
				inStream = readFromSD(temp);
				buffer = HelperTool.readInputStream(inStream);
			}	
		}
		Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
		BitmapDrawable bDrawable = new BitmapDrawable(bitmap);
		return bDrawable;
	}
	
	public static void saveToSD(File file, byte[] buffer) throws Throwable{
		file.createNewFile();
		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(buffer);
		outStream.close();
	}
	
	public static InputStream readFromSD(File file) throws Throwable {
		FileInputStream inStream = new FileInputStream(file);
		return inStream;
	}
	
	public static void clean(Context context){
		File dirFile = new File(path);
		File[] files = dirFile.listFiles();
		int size = files.length;
		for (int i = 0; i < files.length; i++) {
			files[i].delete();
		}
		HelperTool.showMessage(context, "��ɾ��"+size+"���ļ�");
	}
}  